﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Repository;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace Cxuu.Service
{
    [AppService]
    public class ContentCateService
    {
        private readonly ContentCateRepository contentCateDal;
        private readonly ContentRepository contentRepository;
        private readonly AdminUserGroupService _adminUserGroupService;
        private readonly AdminUserDeptService _AdminUserDeptService;
        private readonly ICacheManager _cacheManager;
        private readonly string cacheKey;
        public ContentCateService(ContentCateRepository contentCateRepository, ContentRepository content, AdminUserGroupService adminUserGroupService, ICacheManager cacheManager, AdminUserDeptService adminUserDeptService)
        {
            _cacheManager = cacheManager;
            contentCateDal = contentCateRepository;
            contentRepository = content;
            _adminUserGroupService = adminUserGroupService;
            cacheKey = CacheConst.CACHE_KEY_ARTICLECATE;
            _AdminUserDeptService = adminUserDeptService;
        }


        public async Task<ContentCate> GetInfo(int? id)
        {
            return await contentCateDal.GetAsync(id);
        }

        /// <summary>
        /// 根据权限获取栏目列表
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        public async Task<List<ContentCate>> CateRoleListAsync(int[] cid)
        {
            return await contentCateDal.CateRoleListAsync(cid);
        }

        /// <summary>
        /// 超级管理员获取全部列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<ContentCate>> GetAllAsync()
        {
            List<ContentCate> cate = _cacheManager.Get<List<ContentCate>>(cacheKey);
            if (cate == null)
            {
                cate = await contentCateDal.GetAllListAsync("Id desc");
                _cacheManager.Set(cacheKey, cate, TimeSpan.FromDays(10));
            }
            return cate;
        }

        /// <summary>
        /// 根据 CID 获取 一条栏目数据
        /// </summary>
        /// <returns></returns>
        public async Task<ContentCate> GetOneAsync(int cid)
        {
            List<ContentCate> cates = await GetAllAsync();
            return cates.FirstOrDefault(a => a.Id == cid);
        }
        /// <summary>
        /// 获取指定栏目列表
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="type"></param>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        public async Task<List<ContentCate>> CateListByIdAsync(string cid, bool type = false, string orderBy = "Sort asc")
        {
            string cidCache = cacheKey + MD5Utility.MD5Encrypt16(cid);
            List<ContentCate> cate = _cacheManager.Get<List<ContentCate>>(cidCache);
            if (cate == null)
            {
                cate = await contentCateDal.CateListByIdAsync(cid, type, orderBy);
                _cacheManager.Set(cidCache, cate, TimeSpan.FromDays(1));
            }
            return cate;
        }


        public async Task<object> InsertAsync(ContentCate contentCate)
        {
            _cacheManager.Remove(cacheKey);
            return await contentCateDal.InsertAsync(contentCate);
        }

        public async Task<int> UpdateAsync(ContentCate contentCate)
        {
            _cacheManager.Remove(cacheKey);
            return await contentCateDal.UpdateAsync(contentCate);
        }

        public async Task<int> DeleteByPriKeyAsync(int id)
        {
            Content isContentHave = await contentRepository.GetContentByCidAsync(id);
            if (isContentHave.Id > 0)
                return -1;
            _cacheManager.Remove(cacheKey);
            return await contentCateDal.DeleteByPriKeyAsync(id);
        }


        //获取当前用户部门的栏目权限信息
        public async Task<int[]> GetRoleChannlAsync(int deptId)
        {
            try
            {
                AdminUserDept adminUserDept = await _AdminUserDeptService.GetInfo(deptId);
                string[] channlRole = JsonSerializer.Deserialize<string[]>(adminUserDept.ContentCateRole);
                return Array.ConvertAll(channlRole, int.Parse);
            }
            catch { return null; }
            
        }

        /// <summary>
        /// 查询栏目列表并转换
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<SelectListItem>> GetCategorySelectListItemsAsync(int deptId,int gid, int role = 0)
        {
            List<ContentCate> cates;
            if (role > 0)
            {
                if (gid == 1)
                {
                    cates = await GetAllAsync();
                }
                else
                {
                    int[] cateIdChannl = await GetRoleChannlAsync(deptId);
                    cates = await CateRoleListAsync(cateIdChannl);
                }
            }
            else
            {
                cates = await GetAllAsync();
            }
            return cates.AsSelectListItems();//导出带 select标签样式的数据 
        }
        public async Task<IEnumerable<ViewContentCate>> GetContentCateListAsync(UserInfo adminUser, int role = 0)
        {
            List<ContentCate> cates;
            if (role > 0)
            {
                if (adminUser.Gid == 1)
                {
                    cates = await GetAllAsync();
                }
                else
                {
                    int[] cateIdChannl = await GetRoleChannlAsync(adminUser.DeptId);
                    cates = await CateRoleListAsync(cateIdChannl);
                }
            }
            else
            {
                cates = await GetAllAsync();
            }
            return cates.AsCateListItems();//导出带 所有栏目封装数据
        }

        /// <summary>
        /// 栏目管理列表
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<ViewContentCate>> GetContentCates()
        {
            return await GetCates(0, await GetAllAsync());
        }


        /// <summary>
        /// 递归栏目树
        /// </summary>
        /// <param name="pid">父级Id</param>
        /// <param name="cates">数据源</param>
        /// <returns></returns>
        private async Task<List<ViewContentCate>> GetCates(int pid, List<ContentCate> cates = null)
        {
            var parent = cates.Where(P => P.Pid == pid);
            List<ViewContentCate> lists = new();
            foreach (var item in parent)
            {
                ViewContentCate Childer = new()
                {
                    Id = item.Id,
                    Title = item.Name,
                    Type=item.Type,
                    Theme =item.Theme,
                    Ctheme =item.Ctheme,
                    Ico =item.Ico,
                    Sort=item.Sort,
                    Num = item.Num,
                };
                Childer.Children = await GetSon(Childer, cates);
                if(Childer.Children != null)
                {
                    Childer.HaveChild = true;
                    Childer.Open = true;
                }
                lists.Add(Childer);
            }
            async Task<List<ViewContentCate>> GetSon(ViewContentCate cates, List<ContentCate> sonCates = null)
            {
                if (!sonCates.Exists(x => x.Pid == cates.Id))
                {
                    return null;
                }
                else
                {
                    return await GetCates(cates.Id, sonCates);
                }
            }
            return lists.OrderBy(o => o.Sort).ThenBy(o => o.Id).ToList();
        }
    }
}
